﻿// Sheego.Service.X400
// Copyright(C) 2015 Schwab Versand GmbH
//
// This source file is subject to the Microsoft Public License(Ms-PL).
// http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.
using Sheego.Service.X400.Job.Shared;
using Sheego.Service.X400.Job.Shared.BO;
using Sheego.Service.X400.Job.Shared.Locator;
using Sheego.Service.X400.Job.Shared.Parser;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Sheego.Service.X400.Job.Impl.Parser
{
    class X400MessageParser : IX400MessageParser
    {
        private IFileManager FileManager;
        private IX400AddressParser AddressParser;

        public X400MessageParser(IFileManager fileManager, IX400AddressParser addressParser)
        {
            FileManager = fileManager;
            AddressParser = addressParser;
        }

        #region IX400MessageParser Members

        private static Regex regexHeaderLineQuoted = new Regex(@"^([A-Za-z0-9_]+)\s+=\s+\""(.*)\""$");
        private static Regex regexHeaderLine = new Regex(@"^([A-Za-z0-9_]+)\s+=\s+(.*)$");
        private static string dateFormat = "yyMMddHHmmssZ";
        private static CultureInfo culture = CultureInfo.InvariantCulture;
        public IX400Message Parse(IList<string> FileNames)
        {
            if (FileNames.Count() == 0)
                throw new ArgumentNullException("FileNames");

            var HeaderFileList = FileNames.Where(e => e.EndsWith(".hdr"));
            if (HeaderFileList.Count() != 1)
                throw new ArgumentException("FileNames");


            var Message = JobLocator.GetMessage();

            var headerLines = FileManager.ReadTextFile(HeaderFileList.Single());
            foreach (var line in headerLines)
            {
                // MESSAGE_ID = <2490 15/06/22*A=viaT-smtp;C=de;DDA:RFC-822=dirk.friedenberger(a)schwab.de>
                Match match = regexHeaderLineQuoted.Match(line);
                if (!match.Success)
                    match = regexHeaderLine.Match(line);
                if (!match.Success) continue; //Ignore

                var key = match.Groups[1].Value.ToUpper();
                var value = match.Groups[2].Value;

                switch (key)
                {
                    case "MESSAGE_ID":
                        Message.Id = value;
                        break;
                    case "SUBJECT":
                        Message.Subject = value;
                        break;
                    case "P2_ORIGINATOR":
                        Message.P2Originator = AddressParser.Parse(value);
                        break;
                    case "P7_ORIGINATOR":
                        Message.P7Originator = AddressParser.Parse(value);
                        break;
                    case "CREATION_TIME":
                        Message.CreationTime = DateTime.ParseExact(value, dateFormat, culture);
                        break;
                    case "SUBMISSION_TIME":
                        Message.SubmissionTime = DateTime.ParseExact(value, dateFormat, culture);
                        break;
                    case "BODYPART":
                        //BODYPART = IA5TEXT "dnpbcrvb.001"
                        break;
                    default:
                        //Ignore
                        break;

                }



            }

            //MessageParts
            Message.MessageParts = new List<IX400MessagePart>();
            foreach (var file in FileNames.Where(e => !e.EndsWith(".hdr")).OrderBy(x => x))
            {
                var Part = JobLocator.GetMessagePart();

                Part.Content = FileManager.ReadFile(file);
                Part.ContentLength = Part.Content.Length;
                Part.ContentType = FileManager.ProbeContentType(Part.Content);



                Message.MessageParts.Add(Part);
            }
            return Message;

        }

        #endregion
    }
}
